import os
import json
import hashlib
from datetime import datetime
from flask import session, redirect, url_for
from functools import wraps
from config import USERS_DATA_DIR

# 密码加密函数
def hash_password(password):
    """使用MD5对密码进行加密"""
    return hashlib.md5(password.encode()).hexdigest()

# 检查用户是否存在
def user_exists(username):
    """检查用户是否已经存在"""
    user_file = os.path.join(USERS_DATA_DIR, f"{username}.json")
    return os.path.exists(user_file)

# 创建新用户
def create_user(username, password):
    """创建新用户"""
    user_file = os.path.join(USERS_DATA_DIR, f"{username}.json")
    user_data = {
        'username': username,
        'password': hash_password(password),
        'created_at': datetime.now().isoformat(),
        'ratings': {}
    }
    with open(user_file, 'w', encoding='utf-8') as f:
        json.dump(user_data, f, ensure_ascii=False, indent=2)
    return True

# 验证用户登录
def verify_user(username, password):
    """验证用户登录信息"""
    user_file = os.path.join(USERS_DATA_DIR, f"{username}.json")
    if not os.path.exists(user_file):
        return False
    
    try:
        with open(user_file, 'r', encoding='utf-8') as f:
            user_data = json.load(f)
        return user_data.get('password') == hash_password(password)
    except:
        return False

# 获取用户数据
def get_user_data(username):
    """获取用户数据"""
    user_file = os.path.join(USERS_DATA_DIR, f"{username}.json")
    if not os.path.exists(user_file):
        return None
    
    try:
        with open(user_file, 'r', encoding='utf-8') as f:
            return json.load(f)
    except:
        return None

# 保存用户数据
def save_user_data(username, user_data):
    """保存用户数据"""
    user_file = os.path.join(USERS_DATA_DIR, f"{username}.json")
    with open(user_file, 'w', encoding='utf-8') as f:
        json.dump(user_data, f, ensure_ascii=False, indent=2)

# 保存用户评分
def save_user_rating(username, movie_name, ratings):
    """保存用户对电影的评分"""
    user_data = get_user_data(username)
    if user_data:
        # 添加评分时间戳
        ratings_with_timestamp = ratings.copy()
        ratings_with_timestamp['rated_at'] = datetime.now().isoformat()
        
        # 更新用户评分数据
        user_data['ratings'][movie_name] = ratings_with_timestamp
        save_user_data(username, user_data)
        return True
    return False

# 登录装饰器
def login_required(f):
    """检查用户是否已登录的装饰器"""
    @wraps(f)
    def decorated_function(*args, **kwargs):
        if 'username' not in session:
            return redirect(url_for('login'))
        return f(*args, **kwargs)
    return decorated_function